
<template>
  <div class="app-container">
    <!-- 侧边栏 -->
    <div class="sidebar">
      <h2>非遗管理系统</h2>
      <div class="menu">
        <div class="menu-item" @click="activeMenu = 'project'">
          <span>项目管理</span>
        </div>
        <div class="menu-item" @click="activeMenu = 'user'">
          <span>用户管理</span>
        </div>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 项目管理内容 -->
      <div v-if="activeMenu === 'project'" class="review-container">
        <!-- 原来的项目管理内容保持不变 -->
        <div class="review-header">
          <h2>非遗技术审核</h2>
          <div class="filter-bar">
            <el-select v-model="filter.status" placeholder="审核状态" clearable>
              <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>

            <el-select v-model="filter.category" placeholder="技术分类" clearable>
              <el-option
                  v-for="item in categoryOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>

            <el-input
                v-model="filter.keyword"
                placeholder="搜索标题或传承人"
                clearable
                style="width: 250px"
            >
              <template #append>
                <el-button :icon="Search" @click="fetchData" />
              </template>
            </el-input>
          </div>
        </div>

        <el-table
            :data="tableData"
            style="width: 100%"
            border
            v-loading="loading"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="title" label="技术标题" width="180" />
          <el-table-column prop="userName" label="传承人" width="120" />
          <el-table-column prop="category" label="分类" width="150" />
          <el-table-column prop="type" label="类型" width="100">
            <template #default="{ row }">
              <el-tag :type="getTypeTag(row.type)">
                {{ getTypeName(row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusTag(row.status)">
                {{ getStatusName(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="提交时间" width="180" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button size="small" @click="viewDetail(row)">查看</el-button>
              <el-button
                  size="small"
                  type="success"
                  v-if="row.status === 'pending'"
                  @click="approveTech(row.id)"
              >
                通过
              </el-button>
              <el-button
                  size="small"
                  type="danger"
                  v-if="row.status === 'pending'"
                  @click="rejectTech(row.id)"
              >
                拒绝
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination
              v-model:current-page="pagination.current"
              v-model:page-size="pagination.size"
              :total="pagination.total"
              layout="total, sizes, prev, pager, next, jumper"
              @current-change="fetchData"
              @size-change="fetchData"
          />
        </div>

        <!-- 详情对话框 -->
        <el-dialog v-model="detailVisible" title="技术详情" width="70%">
          <div v-if="currentTech" class="tech-detail">
            <h3>{{ currentTech.title }}</h3>
            <div class="meta-info">
              <span>传承人: {{ currentTech.userName }}</span>
              <span>分类: {{ currentTech.category }}</span>
              <span>类型: {{ getTypeName(currentTech.type) }}</span>
              <span>状态: <el-tag :type="getStatusTag(currentTech.status)">
                {{ getStatusName(currentTech.status) }}
              </el-tag></span>
            </div>

            <div class="description">
              <h4>技术描述</h4>
              <p>{{ currentTech.description }}</p>
            </div>

            <div class="materials">
              <h4>上传材料</h4>
              <div class="material-list">
                <div
                    v-for="(item, index) in currentTech.materials"
                    :key="index"
                    class="material-item"
                >
                  <div v-if="isImage(item.url)" class="image-container">
                    <el-image
                        :src="item.url"
                        :preview-src-list="currentTech.materials
                        .filter(m => isImage(m.url))
                        .map(m => m.url)"
                        fit="cover"
                    />
                  </div>
                  <div v-else-if="isVideo(item.url)" class="video-container">
                    <video controls>
                      <source :src="item.url" type="video/mp4" />
                      您的浏览器不支持视频播放
                    </video>
                  </div>
                  <div v-else class="file-container">
                    <el-icon><Document /></el-icon>
                    <span>{{ item.name }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <template #footer>
            <el-button @click="detailVisible = false">关闭</el-button>
            <el-button
                type="primary"
                v-if="currentTech?.status === 'pending'"
                @click="approveTech(currentTech?.id)"
            >
              通过审核
            </el-button>
            <el-button
                type="danger"
                v-if="currentTech?.status === 'pending'"
                @click="rejectTech(currentTech?.id)"
            >
              拒绝审核
            </el-button>
          </template>
        </el-dialog>
      </div>

      <!-- 用户管理内容 -->
      <div v-if="activeMenu === 'user'" class="user-management">
        <h2>用户管理</h2>
        <div class="user-filter">
          <el-input
              v-model="userFilter.keyword"
              placeholder="搜索用户名或邮箱"
              clearable
              style="width: 250px"
          >
            <template #append>
              <el-button :icon="Search" @click="fetchUserData" />
            </template>
          </el-input>
        </div>

        <el-table
            :data="userData"
            style="width: 100%"
            border
            v-loading="userLoading"
        >
          <el-table-column prop="userId" label="ID" width="80" />
          <el-table-column prop="username" label="用户名" width="180" />
          <el-table-column prop="userSex" label="性别" width="120" />
          <el-table-column prop="profile" label="介绍" width="120" />
          <el-table-column prop="email" label="邮箱" width="200" />
          <el-table-column label="角色" width="120">
            <template #default="{ row }">
              {{ {
              '1': '超级管理员',
              '2': '管理员',
              '3': '传承人',
              '4': '用户'
            }[row.role] || '未知角色' }}
            </template>
          </el-table-column>

          <el-table-column prop="phone" label="电话" width="180" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button size="small" @click="viewUserDetail(row)">查看</el-button>
              <el-button
                  size="small"
                  type="primary"
                  @click="editUser(row.id)"
              >
                编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination
              v-model:current-page="userPagination.current"
              v-model:page-size="userPagination.size"
              :total="userPagination.total"
              layout="total, sizes, prev, pager, next, jumper"
              @current-change="fetchUserData"
              @size-change="fetchUserData"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted,watch } from 'vue'
import { Search, Document } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import {
  getTechList,
  getTechDetail,
  approveTech as apiApproveTech,
  rejectTech as apiRejectTech
} from '@/api/techApi'
import { getUsers } from '@/api/userApi' // 引入用户管理API

// 项目管理相关数据和逻辑（保持不变）
const tableData = ref([])
const loading = ref(false)
const filter = reactive({
  status: '',
  category: '',
  keyword: ''
})
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})
const statusOptions = [
  { value: 'pending', label: '待审核' },
  { value: 'approved', label: '已通过' },
  { value: 'rejected', label: '已拒绝' }
]
const categoryOptions = [
  { value: 'folk-literature', label: '民间文学' },
  { value: 'traditional-music', label: '传统音乐' },
  { value: 'traditional-dance', label: '传统舞蹈' }
  // 其他分类...
]

// 获取项目数据
const fetchData = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.current,
      size: pagination.size,
      ...filter
    }
    const res = await getTechList(params)
    tableData.value = res.data.list
    pagination.total = res.data.total
  } catch (error) {
    console.error('获取数据失败:', error)
  } finally {
    loading.value = false
  }
}

const currentTech = ref(null)
const detailVisible = ref(false)
const viewDetail = async (row) => {
  try {
    const res = await getTechDetail(row.id)
    currentTech.value = res.data
    detailVisible.value = true
  } catch (error) {
    console.error('获取详情失败:', error)
  }
}

const approveTech = async (id) => {
  try {
    await apiApproveTech(id)
    ElMessage.success('审核通过')
    fetchData()
    detailVisible.value = false
  } catch (error) {
    console.error('审核失败:', error)
    ElMessage.error('操作失败')
  }
}

const rejectTech = async (id) => {
  try {
    await apiRejectTech(id)
    ElMessage.success('已拒绝')
    fetchData()
    detailVisible.value = false
  } catch (error) {
    console.error('拒绝失败:', error)
    ElMessage.error('操作失败')
  }
}

const getTypeName = (type) => {
  const types = {
    video: '视频',
    photo: '图片',
    document: '文档',
    audio: '音频'
  }
  return types[type] || type
}

const getTypeTag = (type) => {
  const tags = {
    video: 'primary',
    photo: 'success',
    document: 'warning',
    audio: 'info'
  }
  return tags[type] || ''
}

const getStatusName = (status) => {
  const statusMap = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return statusMap[status] || status
}

const getStatusTag = (status) => {
  const tags = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return tags[status] || ''
}

const isImage = (url) => {
  return /\.(jpg|jpeg|png|gif|webp)$/i.test(url)
}

const isVideo = (url) => {
  return /\.(mp4|webm|ogg)$/i.test(url)
}

// 用户管理相关数据和逻辑
const userData = ref([])
const userLoading = ref(false)
const userFilter = reactive({
  keyword: ''
})
const userPagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 获取用户数据

// 获取角色标签类型（用于 el-tag 的 type）
const getUserRoleTag = (role) => {
  const tagMap = {
    '1': 'danger',   // 超级管理员 - 红色
    '2': 'warning',  // 管理员 - 橙色
    '3': 'success',  // 传承人 - 绿色
    '4': 'info'      // 用户 - 蓝色
  }
  return tagMap[role] || ''
}
const fetchUserData = async () => {
  try {
    userLoading.value = true;

    const res = await getUsers(); // 不传参数，默认获取全部用户
    const allData = res.data; // 注意这里直接是数组，不需要 .list

    // 手动分页计算
    const start = (userPagination.current - 1) * userPagination.size;
    const end = start + userPagination.size;
    userData.value = allData.slice(start, end);

    // 设置总条数
    userPagination.total = allData.length;
  } catch (error) {
    console.error('获取用户数据失败:', error);
    ElMessage.error('获取用户数据失败，请稍后重试');
  } finally {
    userLoading.value = false;
  }
}



// 查看用户详情
const viewUserDetail = (row) => {
  // 查看用户详情的逻辑可以在这里实现
  console.log('查看用户详情:', row)
}

// 编辑用户
const editUser = (id) => {
  // 编辑用户的逻辑可以在这里实现
  console.log('编辑用户:', id)
}

// 获取用户状态名称
const getUserStatusName = (status) => {
  const statusMap = {
    active: '活跃',
    inactive: '禁用'
  }
  return statusMap[status] || status
}

// 获取用户状态标签类型
const getUserStatusTag = (status) => {
  const tags = {
    active: 'success',
    inactive: 'danger'
  }
  return tags[status] || ''
}

// 侧边栏相关逻辑
const activeMenu = ref('project')

// 页面加载时初始化数据
onMounted(() => {
  fetchData()
  fetchUserData()
})
watch(
    () => activeMenu.value,
    (newVal) => {
      if (newVal === 'user') {
        fetchUserData()
      }
    }
)
</script>

<style scoped>
.app-container {
  display: flex;
  min-height: 100vh;
}

.sidebar {
  width: 200px;
  background-color: #f5f5f5;
  padding: 60px 0;
  box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
}

.sidebar h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #3a7d00;
}

.menu {
  list-style: none;
  padding: 0;
  margin: 0;
}

.menu-item {
  padding: 12px 20px;
  cursor: pointer;
  transition: background-color 0.3s;
  display: flex;
  align-items: center;
}

.menu-item:hover {
  background-color: #e9e9e9;
}

.menu-item.active {
  background-color: #3a7d00;
  color: white;
}

.main-content {
  flex: 1;
  padding: 60px 20px;
}

.review-container {
  padding-top: 20px;
}

.review-header {
  margin-bottom: 20px;
}

.review-header h2 {
  font-size: 24px;
  color: #3a7d00;
  margin-bottom: 15px;
}

.filter-bar {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.tech-detail h3 {
  font-size: 20px;
  color: #333;
  margin-bottom: 15px;
}

.meta-info {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  font-size: 14px;
  color: #666;
}

.description {
  margin-bottom: 30px;
}

.description h4 {
  font-size: 16px;
  color: #333;
  margin-bottom: 10px;
}

.description p {
  line-height: 1.8;
  color: #555;
}

.materials h4 {
  font-size: 16px;
  color: #333;
  margin-bottom: 15px;
}

.material-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
}

.material-item {
  border: 1px solid #eee;
  border-radius: 4px;
  overflow: hidden;
}

.image-container {
  height: 150px;
}

.video-container {
  height: 150px;
  background: #000;
}

.video-container video {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.file-container {
  padding: 15px;
  display: flex;
  align-items: center;
  gap: 10px;
  color: #666;
}

.user-management h2 {
  font-size: 24px;
  color: #3a7d00;
  margin-bottom: 20px;
}

.user-filter {
  margin-bottom: 20px;
}
</style>